package com.bjtang.fileSync.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import com.twmacinta.util.MD5;

public class FileMd5 {
	public static String getMd5ByInput(BufferedInputStream in) {
	MD5 md5 = new MD5();	
		// 边读边写
		byte[] bus = new byte[65536];
		int n = -1;
		try {
			while (-1 != (n = in.read(bus))) {
				md5.Update(bus, n);
			}
			// 关闭资源
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 	md5.asHex();
	}
	
	public static String getMd5ByString(String string) {

		// 字符
		MD5 md5 = new MD5();
		try {
			md5.Update(string, null);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("md5出错了");
		}

		return md5.asHex();

	}

	// 文件
	public static String getMd5ByFile(String fileName) {
		String hash = null;
		try {
			hash = MD5.asHex(MD5.getHash(new File(fileName)));

		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("md5计算出错了");
		}
		return hash;

	}

	// 文件
	public static String getMd5ByFile(File file) {
		String hash = null;
		try {
			hash = MD5.asHex(MD5.getHash(file));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("md5计算出错了");
		}
		return hash;

	}
}
